package com.yl.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yl.common.core.domain.AjaxResult;
import com.yl.domain.ConferenceCourseDO;
import com.yl.mapper.ConferenceCourseMapper;
import com.yl.service.ConferenceCourseService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class ConferenceCourseServiceImpl implements ConferenceCourseService {
    @Resource
    ConferenceCourseMapper conferenceCourseMapper;

    private ReentrantLock lock = new ReentrantLock();

    /**
     * 保存/修改
     *
     * @param conferenceCourseDO
     * @author : y
     * @date :  2024/7/10 14:56
     */
    @Override
    public AjaxResult save(ConferenceCourseDO conferenceCourseDO) {
        lock.lock();
        try {
            if (conferenceCourseDO.getConferenceId() == null) {
                return AjaxResult.error("参数不能为空");
            }
            // 添加时间
            conferenceCourseDO.setCreateTime(new Date());
            conferenceCourseMapper.delete(Wrappers.<ConferenceCourseDO>lambdaQuery().eq(ConferenceCourseDO::getConferenceId, conferenceCourseDO.getConferenceId()));
            if (conferenceCourseDO.getConferenceCourseId() == null) {
                conferenceCourseMapper.insert(conferenceCourseDO);
            } else {
                conferenceCourseMapper.updateById(conferenceCourseDO);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            System.out.println("存储内容报错了" + e);

        } finally {
            // 释放锁
            lock.unlock();
        }
        return null;
    }

    /**
     * @param conferenceId
     * @param content
     * @author : y
     * @date :  2024/7/16 21:37
     */
    @Override
    public void websocketSave(Long conferenceId, String content) {
        ConferenceCourseDO courseDO = new ConferenceCourseDO();
        courseDO.setConferenceId(conferenceId);
        courseDO.setContent(content);
        courseDO.setCreateTime(new Date());
        conferenceCourseMapper.delete(Wrappers.<ConferenceCourseDO>lambdaQuery().eq(ConferenceCourseDO::getConferenceId, conferenceId));
        conferenceCourseMapper.insert(courseDO);
    }

    /**
     * @param conferenceCourseDO
     * @author : y
     * @date :  2024/7/10 14:57
     */
    @Override
    public AjaxResult getCourseById(ConferenceCourseDO conferenceCourseDO) {
        List<ConferenceCourseDO> list = conferenceCourseMapper.selectList(Wrappers.<ConferenceCourseDO>lambdaQuery().eq(ConferenceCourseDO::getConferenceId, conferenceCourseDO.getConferenceId()));
        if (list != null && list.size() != 0) {
            return AjaxResult.success(list.get(0));
        } else {
            return AjaxResult.success(new ConferenceCourseDO());
        }
    }
}
